package com.etheart.lyric.htmlparser.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.springframework.stereotype.Service;

import com.etheart.framework.core.util.RegexUtils;
import com.etheart.model.entity.Album;
import com.etheart.model.entity.Singer;
import com.etheart.model.entity.Song;

@Service("htmlparser_AlbumParseService")
public class AlbumParseService {
	private static final Log logger = LogFactory
			.getLog(AlbumParseService.class);

	public Album getAlbum(Parser parser, String fileName) {
		String idStr = RegexUtils.getMatcheGroup(".*album_([0-9]*)\\.html",
				fileName);
		Album album = new Album();
		album.setNetId(idStr);
		return getAlbum(parser, album);
	}

	private Album getAlbum(Parser parser, Album album) {
			// 得到专辑名称
			try {
				String albumName = parseAlbumName(parser);
				album.setAlbumname(albumName);
			} catch (Exception e) {
				logger.debug(album.getNetId()+":专辑名称转化错误");
			}
			
			// 得到专辑介绍
			try {
				String albumIntro = parseAlbumIntro(parser);
				album.setIntro(albumIntro);
			} catch (Exception e) {
				logger.debug(album.getNetId()+":专辑介绍转化错误");
			}
			
			// 得到专辑发行 语种 公司 发行时间 等
			String[] strs=null;
			try {
				strs = parseAlbumLanguage(parser);
				if (strs!=null&&strs.length>=3) {
					album.setLanguage(strs[0]);
					album.setConame(strs[1]);
				}
			} catch (Exception e) {
				logger.debug(album.getNetId()+":语种转化错误");
			}
			
			try {
				album.setPublishtime(com.etheart.framework.core.util.DateUtils.parseDate(strs[2]));
			} catch (Exception e2) {
				logger.debug(album.getNetId()+":发行时间转化错误");
			}
			// 专辑图片
			try{
				String pic = parseAlbumImg(parser);
				album.setPicture(pic);
			} catch (Exception e2) {
				logger.debug(album.getNetId()+":专辑图片转化错误");
			}
	

		return album;
	}

	private String parseAlbumImg(Parser parser) throws ParserException {
		parser.reset();
		NodeFilter imgFilter = new AndFilter(new TagNameFilter("img"),new HasAttributeFilter("width", "150")); 
	
		// 得到专辑图片地址
		NodeList nodeList = parser.parse(imgFilter);
		for (int i = 0; i < nodeList.size(); i++) {
			Tag tag = (Tag) nodeList.elementAt(i);
			String src = tag.getAttribute("src");
			if (src.indexOf("photo/album") != -1) {
				return src.replace("http://imgcache.qq.com/music/", "");
			}
		}
		return null;
	}

	private String[] parseAlbumLanguage(Parser parser) throws ParserException {
		parser.reset();
		NodeFilter filter = new TagNameFilter("p");
		NodeList nodeList = parser.parse(filter);
		for (int i = 0; i < nodeList.size(); i++) {
			Tag tag = (Tag) nodeList.elementAt(i);
			String tagPHtml = tag.toHtml();
			if (tagPHtml.indexOf("唱片公司") != -1) {
				// 得到发行公司 发行时间 和语言
				tagPHtml = tagPHtml.replaceAll("\r\n", "");
				return RegexUtils.getMatcheGroups(
				".*语言：</strong>([^<]*).*</strong><a[^>]*>([^<]*)</a.*</strong>([^<]*)</p>.*",
				tagPHtml, 3);
				// String language = matcher.group(1);
				// String coName = matcher.group(2);
				// String pubtime = matcher.group(3);
			}
		}
		return null;
	}

	private String parseAlbumIntro(Parser parser) throws ParserException {
		parser.reset();
		NodeFilter filter = new AndFilter(new TagNameFilter("p"),
				new HasAttributeFilter("class", "about"));
		NodeList nodeList = parser.parse(filter);
		if (nodeList.size() <= 0) {
			return null;
		}
		Tag tag = (Tag) nodeList.elementAt(0);
		return tag.toPlainTextString().replace("专辑介绍：", "");
	}

	public List<Song> getSongs(Parser parser) {
		List<Song> songs = new ArrayList<Song>(10);
		parser.reset();
	
		NodeFilter filter = new AndFilter(new TagNameFilter("td"),new HasAttributeFilter("class","song"));
		NodeList nodeList;
		try {
			nodeList = parser.parse(filter);
		} catch (ParserException e) {
			logger.error("song解析失败:重要", e);
			e.printStackTrace();
			return songs;
		}
		for (int i = 0; i < nodeList.size();i++) {
			Song song = new Song();
			Tag tag = (Tag) nodeList.elementAt(i);
			String tagHtml = tag.toHtml();
			String id =null;
			String singerid = null;
			try {
				id = RegexUtils.getMatcheGroup(".*?id=([0-9]*)\".*", tagHtml);
				song.setNetId(id);
			} catch (Exception e) {
				logger.debug("歌曲netid错误");
			}
			
			
			String name = tag.getAttribute("title");
			song.setSongname(name);
			songs.add(song);
		}
		return songs;
	}

	private String parseAlbumName(Parser parser) throws ParserException {
		parser.reset();
		NodeFilter filter = new TagNameFilter("h2");
		NodeList nodeList = parser.parse(filter);
		for (int i = 0; i < nodeList.size();) {
			Node h2 = nodeList.elementAt(i);
			Tag h2Tag = (Tag) h2;
			return h2Tag.getAttribute("title");
		}
		return null;
	}
	public List<Song> matchSongs(Parser parser , Singer singer,Album album){
		List<Song> songs = new ArrayList<Song>(10);
		parser.reset();
	
		NodeFilter filter = new AndFilter(new TagNameFilter("td"),new HasAttributeFilter("class","data"));
		NodeList nodeList;
		try {
			nodeList = parser.parse(filter);
		} catch (ParserException e) {
			logger.error("song解析失败:重要", e);
			e.printStackTrace();
			return songs;
		}
		for (int i = 0; i < nodeList.size();i++) {
			Song song = new Song();
			Tag tag = (Tag) nodeList.elementAt(i);
			String tagHtml = tag.toHtml();
			String id =null;
			String singerid = null;
			try {
				id = RegexUtils.getMatcheGroup(".*mid=([0-9]*)\\|msong.*", tagHtml);
				song.setNetId(id);
			} catch (Exception e) {
				logger.debug("歌曲netid错误：albumnetId:"+album.getNetId()+",singerNetID:"+singer.getNetId());
			}
			try {
				singerid = RegexUtils.getMatcheGroup(".*\\|msingerid=([0-9]*)\\|.*", tagHtml);
				if (singerid.endsWith(singer.getNetId())  ) {
					song.setSinger(singer);
				}else{
					Singer singer2 = new Singer();
					singer2.setNetId(singerid);
					song.setSinger(singer2);
				}
				
			} catch (Exception e) {
				logger.debug("歌手netid错误：albumnetId:"+album.getNetId()+",singerNetID:"+singer.getNetId());
			}
			
			String name = tag.getAttribute("title");
			song.setSongname(name);
			songs.add(song);
		}
		return songs;
	}
}
